<template>
  <div class="user-recipes">
    <el-tabs v-model="activeTab" class="recipe-tabs">
      <el-tab-pane label="已审核菜谱" name="approved">
        <div class="recipe-grid">
          <el-card v-for="recipe in approvedRecipes" :key="recipe.cookbId" class="recipe-card">
            <img :src="recipe.recipeImg" class="recipe-image">
            <div class="recipe-info">
              <h3>{{ recipe.cookbName }}</h3>
              <p class="description">{{ recipe.content }}</p>
              <div class="stats">
                <span>
                  <el-icon>
                    <Star />
                  </el-icon>
                  {{ recipe.favoriteCount }} 收藏
                </span>
                <span>
                  <el-icon>
                    <ChatDotRound />
                  </el-icon>
                  {{ recipe.commentCount }} 评论
                </span>
              </div>
              <div class="actions">
                <el-button type="primary" @click="viewComments(recipe)">
                  查看评论
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <el-tab-pane label="待审核菜谱" name="pending">
        <div class="recipe-grid">
          <el-card v-for="recipe in pendingRecipes" :key="recipe.cookbId" class="recipe-card">
            <img :src="recipe.recipeImg" class="recipe-image">
            <div class="recipe-info">
              <h3>{{ recipe.cookbName }}</h3>
              <p class="description">{{ recipe.content }}</p>
              <div class="status">
                <el-tag type="warning">审核中</el-tag>
              </div>
              <div class="actions">
                <el-button type="primary" @click="editRecipe(recipe)">
                  编辑
                </el-button>
                <el-button type="danger" @click="deleteRecipe(recipe)">
                  删除
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
  <Dialog :title="dialog.title" :width="dialog.width" :height="dialog.height" :visible="dialog.visible"
    @on-close="onClose" @on-confirm="commit">
    <el-form :model="recipeForm" label-width="80px" ref="editFormRef">
      <el-form-item label="菜谱名称">
        <el-input v-model="recipeForm.cookbName" placeholder="请输入菜谱名称"></el-input>
      </el-form-item>
      <el-form-item label="菜系">
        <el-select v-model="recipeForm.cuisine" placeholder="请选择所属菜系" clearable>
          <el-option v-for="item in cuisineOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>

      </el-form-item>
      <el-form-item label="地方">
        <el-input v-model="recipeForm.place" placeholder="请输入地方"></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <el-input type="textarea" v-model="recipeForm.content" :rows="4" placeholder="请输入菜谱内容"></el-input>
      </el-form-item>
    </el-form>
    <UploadImg ref="imageUploader"></UploadImg>
  </Dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { Star, ChatDotRound } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { useUserStore } from '@/store/islogin'
import { deleteRecipeApi, editRecipeApi, getRecipesApi } from '@/api/food'
import UploadImg from '@/components/upload/UploadImg.vue';
import { StatusType, type FoodTable } from '@/api/food/foodTable'
import { useFoodStore } from '@/store/comment'
import router from '@/router'
import useDialog from '@/hooks/usedialog'
import Dialog from '@/components/dialog/Dialog.vue'
import { useImageUrlStore } from '@/store/imgUrl'
const useUrl = useImageUrlStore()
const useUser = useUserStore()
const useFood = useFoodStore()
const activeTab = ref('approved')
//弹框数据
const { dialog, onClose, onConfirm, onShow } = useDialog()
//获取form表单组件实例
const editFormRef = ref<FormInstance>();
// 模拟数据，实际项目中应该从API获取
const approvedRecipes = ref([] as any[])

const pendingRecipes = ref([] as any[])

const recipeForm = reactive<FoodTable>({
  cookbId: '',
  userId: '',
  adminId: '',
  cookbName: '',
  cuisine: '',
  place: '',
  content: '',
  recipeImg: '',
  createTime: '',
  updateTime: '',
  status: StatusType.Prohibit,
  reviewedTime: '',
  commentCount: 0,
  favoriteCount: 0
})

const viewComments = (recipe: any) => {
  useFood.setSelectedFood(recipe)
  router.push("/comment")
}


const cuisineOptions = reactive([
  { value: '川菜', label: '川菜' },
  { value: '湘菜', label: '湘菜' },
  { value: '粤菜', label: '粤菜' },
  { value: '闽菜', label: '闽菜' },
  { value: '苏菜', label: '苏菜' },
  { value: '浙菜', label: '浙菜' },
  { value: '徽菜', label: '徽菜' },
  { value: '鲁菜', label: '鲁菜' },
  { value: '其他', label: '其他' }
]);


const editRecipe = (recipe: any) => {
  onShow()
  Object.assign(recipeForm, recipe)
  console.log(recipeForm)
}

const deleteRecipe = (recipe: any) => {
  ElMessageBox.confirm(
    '确定要删除这个菜谱吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    // 实现删除菜谱的逻辑
    const res = await deleteRecipeApi(recipe.cookbId)
    if (res.code == 200) {
      ElMessage.success(res.msg)
      getRecipeList()
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}
//搜索参数
const keyword = reactive<FoodTable>({
  cookbId: '',
  userId: '',
  adminId: '',
  cookbName: '',
  cuisine: '',
  place: '',
  content: '',
  recipeImg: '',
  createTime: '',
  updateTime: '',
  status: StatusType.Prohibit,
  reviewedTime: '',
  commentCount: 0,
  favoriteCount: 0
})
const getRecipeList = async () => {
  if (useUser.user) {
    keyword.userId = useUser.user.userId
    const res = await getRecipesApi(keyword)
    if (res.code == 200) {
      ElMessage.success(res.msg)
      approvedRecipes.value = res.data.filter((recipe: { status: number }) => recipe.status === 1);
      pendingRecipes.value = res.data.filter((recipe: { status: number }) => recipe.status === 0);
      console.log(approvedRecipes.value)
    }
  } else {
    ElMessage.error("请进行登录")
  }
}
//修改菜谱提交按钮
const commit = () => {
  //表单验证
  editFormRef.value?.validate(async (valid) => {
    if (valid) {
      if (useUrl.getImageUrl) {
        ElMessage.success("上传菜谱新图片成功")
        recipeForm.recipeImg = useUrl.getImageUrl
        const res = await editRecipeApi(recipeForm)
        if (res.code == 200) {
          ElMessage.success(res.msg)
          useUrl.deleteImageUrl()
          getRecipeList()
          onClose()
          editFormRef.value?.resetFields()
        }
      } else {
        const res = await editRecipeApi(recipeForm)
        if (res.code == 200) {
          ElMessage.success(res.msg)
          getRecipeList()
          onClose()
          editFormRef.value?.resetFields()
        }
      }
    }
  });
}
onMounted(() => {
  getRecipeList()
})
</script>

<style scoped>
.user-recipes {
  padding: 20px;
}

.recipe-tabs {
  margin-bottom: 20px;
}

.recipe-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.recipe-card {
  transition: transform 0.3s;
}

.recipe-card:hover {
  transform: translateY(-5px);
}

.recipe-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.recipe-info {
  padding: 15px;
}

.recipe-info h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
}

.description {
  color: #666;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.stats {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
  color: #666;
}

.stats span {
  display: flex;
  align-items: center;
  gap: 5px;
}

.actions {
  display: flex;
  gap: 10px;
}

.status {
  margin-bottom: 15px;
}
</style>